package com.pubinfo.passbook.data.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pubinfo.passbook.common.entity.TFeedbackFile;
import com.pubinfo.passbook.common.entity.TFileInfo;
import com.pubinfo.passbook.common.mapper.TFeedbackFileMapper;
import com.pubinfo.passbook.data.service.TFeedbackFileService;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuhong
 * @since 2022-02-28
 */
@Service
public class TFeedbackFileServiceImpl extends ServiceImpl<TFeedbackFileMapper, TFeedbackFile> implements TFeedbackFileService {

    @Value("${file.feedBack}")
    private String filePath;

    @Override
    public Boolean saveFeedbackFile(List<MultipartFile> multipartFiles,String feedbackId) {

        if(CollectionUtils.isEmpty(multipartFiles))return true;
        for(MultipartFile multipartFile:multipartFiles)
        {
            TFeedbackFile tFeedbackFile = createTFileInfoByMultipartFile(multipartFile, filePath, multipartFile.getOriginalFilename());
            tFeedbackFile.setFeedbackId(feedbackId);
            save(tFeedbackFile);
            upload(multipartFile,tFeedbackFile.getPath());
        }
        return true;
    }

    @SneakyThrows
    private void upload(MultipartFile file, String path) {
        file.transferTo(new File(path));
    }

    private TFeedbackFile createTFileInfoByMultipartFile(MultipartFile file, String path, String name) {

        File tFile = new File(path);
        if (!tFile.exists()) {//如果文件夹不存在
            tFile.mkdirs();//创建文件夹
        }

        TFeedbackFile tFeedbackFile = new TFeedbackFile();
        tFeedbackFile.setName(file.getOriginalFilename());
        tFeedbackFile.setContentType(file.getContentType());
        tFeedbackFile.setSize(file.getSize());
        tFeedbackFile.setPath(path +
                new SimpleDateFormat("yyyyMMddHHmm").format(new Date())
                + name);
        tFeedbackFile.setIsDelete(1);
//        tFileInfo.setCreateBy(userInfoService.getCurrentAcctId());
        return tFeedbackFile;
    }
}
